// ==UserScript==
// @name        网页图片获取器
// @namespace   Violentmonkey Scripts
// @match       *://*/*
// @grant       GM_registerMenuCommand
// @grant       GM_setClipboard
// @grant       GM_download
// @version     1.0
// @author      Cursor
// @icon        https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/%E7%BD%91%E9%A1%B5%E5%9B%BE%E7%89%87%E8%8E%B7%E5%8F%96%E5%99%A8/Web-picture.png
// @description 获取网页上所有图片的暴力猴脚本
// ==/UserScript==

(function() {
  'use strict';
  
  // 注册菜单命令
  GM_registerMenuCommand('复制所有图片链接', copyAllImageLinks);
  GM_registerMenuCommand('下载所有图片', downloadAllImages);
  GM_registerMenuCommand('显示图片预览面板', showImagePanel);
  
  // 获取页面上所有图片
  function getAllImages() {
    const images = [];
    
    // 获取所有img标签
    document.querySelectorAll('img').forEach(img => {
      if (img.src && img.src.trim() !== '' && !images.includes(img.src)) {
        images.push(img.src);
      }
    });
    
    // 获取CSS背景图片
    const allElements = document.querySelectorAll('*');
    allElements.forEach(el => {
      const style = window.getComputedStyle(el);
      const backgroundImage = style.backgroundImage;
      
      if (backgroundImage && backgroundImage !== 'none') {
        const urls = backgroundImage.match(/url\(['"]?(.*?)['"]?\)/g);
        if (urls) {
          urls.forEach(url => {
            const cleanUrl = url.replace(/url\(['"]?(.*?)['"]?\)/, '$1');
            if (cleanUrl && !images.includes(cleanUrl)) {
              images.push(cleanUrl);
            }
          });
        }
      }
    });
    
    // 查找内联样式中的背景图片
    document.querySelectorAll('[style*="background"]').forEach(el => {
      const inlineStyle = el.getAttribute('style');
      if (inlineStyle) {
        const match = inlineStyle.match(/background(-image)?\s*:\s*url\(['"]?(.*?)['"]?\)/);
        if (match && match[2] && !images.includes(match[2])) {
          images.push(match[2]);
        }
      }
    });
    
    return images;
  }
  
  // 复制所有图片链接到剪贴板
  function copyAllImageLinks() {
    const images = getAllImages();
    
    if (images.length === 0) {
      alert('未在当前页面找到图片！');
      return;
    }
    
    const text = images.join('\n');
    GM_setClipboard(text);
    
    alert(`已复制 ${images.length} 个图片链接到剪贴板`);
  }
  
  // 下载所有图片
  function downloadAllImages() {
    const images = getAllImages();
    
    if (images.length === 0) {
      alert('未在当前页面找到图片！');
      return;
    }
    
    if (!confirm(`确定要下载全部 ${images.length} 张图片吗？`)) {
      return;
    }
    
    let counter = 0;
    
    images.forEach((url, index) => {
      setTimeout(() => {
        // 从URL中提取文件名，如果没有则使用索引
        let filename = url.split('/').pop();
        
        // 处理URL中的查询参数
        if (filename.includes('?')) {
          filename = filename.split('?')[0];
        }
        
        // 如果没有扩展名，尝试添加
        if (!filename.includes('.')) {
          if (url.includes('.jpg') || url.includes('.jpeg')) {
            filename += '.jpg';
          } else if (url.includes('.png')) {
            filename += '.png';
          } else if (url.includes('.gif')) {
            filename += '.gif';
          } else if (url.includes('.webp')) {
            filename += '.webp';
          } else {
            filename += '.jpg'; // 默认扩展名
          }
        }
        
        // 添加索引前缀以保持顺序
        filename = `${(index + 1).toString().padStart(3, '0')}_${filename}`;
        
        GM_download(url, filename);
      }, index * 500); // 每500毫秒下载一张，避免浏览器卡死
      
      counter++;
    });
    
    alert(`开始下载 ${counter} 张图片，请注意浏览器下载通知`);
  }
  
  // 创建并显示图片预览面板
  function showImagePanel() {
    const images = getAllImages();
    
    if (images.length === 0) {
      alert('未在当前页面找到图片！');
      return;
    }
    
    // 用于跟踪选中的图片
    const selectedImages = new Set();
    
    // 创建面板
    const panel = document.createElement('div');
    panel.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 90%;
      max-width: 800px;
      height: 90vh;
      max-height: 800px;
      background: white;
      color: #333;
      overflow-y: auto;
      z-index: 9999999;
      box-sizing: border-box;
      font-family: Arial, sans-serif;
      border-radius: 10px;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
      padding: 0;
    `;
    
    // 添加标题区域
    const titleContainer = document.createElement('div');
    titleContainer.style.cssText = 'display: flex; justify-content: space-between; align-items: center; padding: 15px; position: sticky; top: 0; background: #f8f8f8; z-index: 1; border-bottom: 1px solid #eaeaea; border-radius: 10px 10px 0 0;';
    
    // 添加标题
    const title = document.createElement('h2');
    title.textContent = `找到 ${images.length} 张图片`;
    title.style.cssText = 'margin: 0; font-size: 18px; color: #333;';
    titleContainer.appendChild(title);
    
    // 添加关闭按钮
    const closeButton = document.createElement('button');
    closeButton.innerHTML = '&times;';
    closeButton.style.cssText = 'background: #f44336; color: white; border: none; border-radius: 50%; width: 28px; height: 28px; font-size: 18px; cursor: pointer; display: flex; justify-content: center; align-items: center; line-height: 1;';
    closeButton.onclick = () => {
      overlay.remove();
      panel.remove();
    };
    closeButton.title = '关闭面板';
    titleContainer.appendChild(closeButton);
    
    panel.appendChild(titleContainer);
    
    // 添加内容容器
    const contentContainer = document.createElement('div');
    contentContainer.style.cssText = 'padding: 15px;';
    
    // 添加选择按钮区
    const selectionContainer = document.createElement('div');
    selectionContainer.style.cssText = 'display: flex; gap: 10px; margin-bottom: 15px;';
    
    // 添加全选按钮
    const selectAllButton = document.createElement('button');
    selectAllButton.textContent = '全选';
    selectAllButton.style.cssText = 'padding: 5px 10px; cursor: pointer; background: #9C27B0; color: white; border: none; border-radius: 4px; font-size: 14px; flex: 1;';
    selectAllButton.onclick = () => {
      document.querySelectorAll('.image-checkbox').forEach(checkbox => {
        checkbox.checked = true;
        selectedImages.add(checkbox.value);
      });
      updateSelectedCount();
    };
    selectionContainer.appendChild(selectAllButton);
    
    // 添加反选按钮
    const invertSelectionButton = document.createElement('button');
    invertSelectionButton.textContent = '反选';
    invertSelectionButton.style.cssText = 'padding: 5px 10px; cursor: pointer; background: #9C27B0; color: white; border: none; border-radius: 4px; font-size: 14px; flex: 1;';
    invertSelectionButton.onclick = () => {
      document.querySelectorAll('.image-checkbox').forEach(checkbox => {
        checkbox.checked = !checkbox.checked;
        if (checkbox.checked) {
          selectedImages.add(checkbox.value);
        } else {
          selectedImages.delete(checkbox.value);
        }
      });
      updateSelectedCount();
    };
    selectionContainer.appendChild(invertSelectionButton);
    
    // 添加取消选择按钮
    const clearSelectionButton = document.createElement('button');
    clearSelectionButton.textContent = '取消选择';
    clearSelectionButton.style.cssText = 'padding: 5px 10px; cursor: pointer; background: #9C27B0; color: white; border: none; border-radius: 4px; font-size: 14px; flex: 1;';
    clearSelectionButton.onclick = () => {
      document.querySelectorAll('.image-checkbox').forEach(checkbox => {
        checkbox.checked = false;
        selectedImages.clear();
      });
      updateSelectedCount();
    };
    selectionContainer.appendChild(clearSelectionButton);
    
    contentContainer.appendChild(selectionContainer);
    
    // 添加选中计数
    const selectedCountContainer = document.createElement('div');
    selectedCountContainer.style.cssText = 'margin-bottom: 15px; font-size: 14px; color: #555;';
    selectedCountContainer.id = 'selected-count';
    selectedCountContainer.textContent = '已选择: 0 张图片';
    contentContainer.appendChild(selectedCountContainer);
    
    // 添加按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.style.cssText = 'display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 15px;';
    
    // 添加复制按钮
    const copyButton = document.createElement('button');
    copyButton.textContent = '复制所有链接';
    copyButton.style.cssText = 'padding: 8px 5px; cursor: pointer; background: #4CAF50; color: white; border: none; border-radius: 4px; font-size: 14px;';
    copyButton.onclick = copyAllImageLinks;
    buttonContainer.appendChild(copyButton);
    
    // 添加复制选中链接按钮
    const copySelectedButton = document.createElement('button');
    copySelectedButton.textContent = '复制选中链接';
    copySelectedButton.style.cssText = 'padding: 8px 5px; cursor: pointer; background: #4CAF50; color: white; border: none; border-radius: 4px; font-size: 14px;';
    copySelectedButton.onclick = () => {
      if (selectedImages.size === 0) {
        alert('请先选择图片！');
        return;
      }
      
      const text = Array.from(selectedImages).join('\n');
      GM_setClipboard(text);
      alert(`已复制 ${selectedImages.size} 个图片链接到剪贴板`);
    };
    buttonContainer.appendChild(copySelectedButton);
    
    // 添加下载按钮
    const downloadButton = document.createElement('button');
    downloadButton.textContent = '下载所有图片';
    downloadButton.style.cssText = 'padding: 8px 5px; cursor: pointer; background: #2196F3; color: white; border: none; border-radius: 4px; font-size: 14px;';
    downloadButton.onclick = downloadAllImages;
    buttonContainer.appendChild(downloadButton);
    
    // 添加下载选中图片按钮
    const downloadSelectedButton = document.createElement('button');
    downloadSelectedButton.textContent = '下载选中图片';
    downloadSelectedButton.style.cssText = 'padding: 8px 5px; cursor: pointer; background: #2196F3; color: white; border: none; border-radius: 4px; font-size: 14px;';
    downloadSelectedButton.onclick = () => {
      if (selectedImages.size === 0) {
        alert('请先选择图片！');
        return;
      }
      
      if (!confirm(`确定要下载选中的 ${selectedImages.size} 张图片吗？`)) {
        return;
      }
      
      let counter = 0;
      const selectedArray = Array.from(selectedImages);
      
      selectedArray.forEach((url, index) => {
        setTimeout(() => {
          // 从URL中提取文件名，如果没有则使用索引
          let filename = url.split('/').pop();
          
          // 处理URL中的查询参数
          if (filename.includes('?')) {
            filename = filename.split('?')[0];
          }
          
          // 如果没有扩展名，尝试添加
          if (!filename.includes('.')) {
            if (url.includes('.jpg') || url.includes('.jpeg')) {
              filename += '.jpg';
            } else if (url.includes('.png')) {
              filename += '.png';
            } else if (url.includes('.gif')) {
              filename += '.gif';
            } else if (url.includes('.webp')) {
              filename += '.webp';
            } else {
              filename += '.jpg'; // 默认扩展名
            }
          }
          
          // 添加索引前缀以保持顺序
          filename = `${(index + 1).toString().padStart(3, '0')}_${filename}`;
          
          GM_download(url, filename);
        }, index * 500); // 每500毫秒下载一张，避免浏览器卡死
        
        counter++;
      });
      
      alert(`开始下载 ${counter} 张图片，请注意浏览器下载通知`);
    };
    buttonContainer.appendChild(downloadSelectedButton);
    
    contentContainer.appendChild(buttonContainer);
    
    // 创建背景蒙层按钮（将面板推到后台）
    const backgroundButton = document.createElement('button');
    backgroundButton.textContent = '后台运行';
    backgroundButton.style.cssText = 'width: 100%; padding: 8px 10px; cursor: pointer; margin-bottom: 15px; background: #FF9800; color: white; border: none; border-radius: 4px; font-size: 14px;';
    backgroundButton.onclick = () => {
      // 保存当前选中的图片
      const currentSelectedImages = new Set(selectedImages);
      
      // 隐藏面板和背景
      panel.style.display = 'none';
      overlay.style.display = 'none';
      
      // 创建一个恢复按钮
      const restoreButton = document.createElement('button');
      restoreButton.textContent = '恢复图片面板';
      restoreButton.style.cssText = `
        position: fixed;
        bottom: 10px;
        right: 10px;
        padding: 8px 10px;
        background: #f44336;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        z-index: 10000000;
        font-size: 14px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.3);
      `;
      restoreButton.onclick = () => {
        panel.style.display = 'block';
        overlay.style.display = 'block';
        restoreButton.remove();
      };
      document.body.appendChild(restoreButton);
    };
    contentContainer.appendChild(backgroundButton);
    
    // 创建图片网格容器
    const gridContainer = document.createElement('div');
    gridContainer.style.cssText = 'display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px;';
    
    // 更新选中计数的函数
    function updateSelectedCount() {
      const countElement = document.getElementById('selected-count');
      if (countElement) {
        countElement.textContent = `已选择: ${selectedImages.size} 张图片`;
      }
    }
    
    // 添加所有图片预览
    images.forEach((url, index) => {
      const container = document.createElement('div');
      container.style.cssText = 'background: #f5f5f5; border-radius: 5px; padding: 10px; display: flex; flex-direction: column; box-shadow: 0 1px 3px rgba(0,0,0,0.1);';
      
      // 添加复选框和图片的包装器
      const checkboxWrapper = document.createElement('div');
      checkboxWrapper.style.cssText = 'display: flex; align-items: flex-start; margin-bottom: 5px;';
      
      // 添加复选框
      const checkbox = document.createElement('input');
      checkbox.type = 'checkbox';
      checkbox.className = 'image-checkbox';
      checkbox.value = url;
      checkbox.style.cssText = 'margin-right: 5px; cursor: pointer;';
      checkbox.addEventListener('change', function() {
        if (this.checked) {
          selectedImages.add(this.value);
        } else {
          selectedImages.delete(this.value);
        }
        updateSelectedCount();
      });
      checkboxWrapper.appendChild(checkbox);
      
      const imgContainer = document.createElement('div');
      imgContainer.style.cssText = 'flex-grow: 1;';
      
      const img = document.createElement('img');
      img.src = url;
      img.style.cssText = 'width: 100%; height: auto; display: block; cursor: pointer; object-fit: cover; max-height: 150px; border-radius: 3px;';
      img.onclick = () => window.open(url, '_blank');
      img.title = '点击在新标签页打开';
      img.loading = 'lazy'; // 延迟加载提高性能
      imgContainer.appendChild(img);
      
      checkboxWrapper.appendChild(imgContainer);
      container.appendChild(checkboxWrapper);
      
      const indexSpan = document.createElement('span');
      indexSpan.textContent = `#${index + 1}`;
      indexSpan.style.cssText = 'font-weight: bold; font-size: 12px; color: #555;';
      container.appendChild(indexSpan);
      
      const copyLinkButton = document.createElement('button');
      copyLinkButton.textContent = '复制链接';
      copyLinkButton.style.cssText = 'margin-top: 5px; padding: 4px; font-size: 12px; cursor: pointer; background: #f0f0f0; color: #333; border: 1px solid #ddd; border-radius: 3px;';
      copyLinkButton.onclick = (e) => {
        e.stopPropagation();
        GM_setClipboard(url);
        copyLinkButton.textContent = '已复制!';
        setTimeout(() => {
          copyLinkButton.textContent = '复制链接';
        }, 1000);
      };
      container.appendChild(copyLinkButton);
      
      gridContainer.appendChild(container);
    });
    
    contentContainer.appendChild(gridContainer);
    panel.appendChild(contentContainer);
    
    // 创建半透明背景遮罩
    const overlay = document.createElement('div');
    overlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 9999998;
    `;
    overlay.onclick = (e) => {
      // 点击遮罩时防止关闭面板，改为点击遮罩外部区域关闭
      e.stopPropagation();
    };
    
    // 添加到页面
    document.body.appendChild(overlay);
    document.body.appendChild(panel);
    
    // 添加移动端触摸滑动支持
    let touchStartY = 0;
    panel.addEventListener('touchstart', (e) => {
      touchStartY = e.touches[0].clientY;
    }, {passive: true});
    
    panel.addEventListener('touchmove', (e) => {
      const touchY = e.touches[0].clientY;
      const scrollTop = panel.scrollTop;
      const scrollHeight = panel.scrollHeight;
      const clientHeight = panel.clientHeight;
      
      // 如果已经滚动到顶部或底部，阻止默认行为以防止整个页面滚动
      if ((scrollTop <= 0 && touchY > touchStartY) || 
          (scrollTop + clientHeight >= scrollHeight && touchY < touchStartY)) {
        e.preventDefault();
      }
    }, {passive: false});
  }
})(); 